﻿

using Nexia.FluentHtmlElements.IoC;

namespace Nexia.FluentHtmlElements.Utilities
{
	public class PlainTextConversion
	{
		public static readonly int TrimLengthVariance = 20;

		public PlainTextConversion()
		{
			HtmlStripper = DependencyFactory.GetInstance<IHtmlStripper>();
			StringTrimmer = DependencyFactory.GetInstance<IStringTrimmer>();
		}

		public PlainTextConversion(IHtmlStripper htmlStripper, IStringTrimmer stringTrimmer)
		{
			HtmlStripper = htmlStripper;
			StringTrimmer = stringTrimmer;
		}

		private readonly IHtmlStripper HtmlStripper;
		private readonly IStringTrimmer StringTrimmer;

		/// <summary>
		/// Takes a string and trims it down to the approximate cutOff length after removing any html.
		/// </summary>
		/// <remarks>This trimmer is word aware and will attempt to trim the string at a word boundary.</remarks>
		/// <param name="text">text to trim</param>
		/// <param name="cutOff">The approximate cut off point</param>
		/// <returns>the trimmed text</returns>
		public string ConvertToPlainTextAndTrim(string text, int cutOff)
		{
			if (string.IsNullOrEmpty(text))
				return string.Empty;

			var plaintext = HtmlStripper.ConvertToPlainText(text);

			if (plaintext.Length <= cutOff)
				return plaintext;

			var trimmedText = StringTrimmer.WordAwareTrim(plaintext, cutOff, TrimLengthVariance);

			return string.Concat(trimmedText, "...");
		}
	}
}
